package com.jixi.common.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jixi.common.exception.HttpRequestException;
import okhttp3.*;

import java.io.IOException;

public class CozeOauthAccessTokenUtil {
	
	/**
	 * 获取 Coze Oauth Access Token
	 */
	public static String getAccessToken(Long educationId) {
		final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
		MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
		String requestBody = "{\"grant_type\":\"urn:ietf:params:oauth:grant-type:jwt-bearer\",\"duration_seconds\":86399}";
		RequestBody body = RequestBody.Companion.create(requestBody, mediaType);
		Request request = new Request.Builder()
				.url("https://api.coze.cn/api/permission/oauth2/token")
				.post(body)
				.addHeader("Content-Type", "application/json")
				.addHeader("Authorization", "Bearer " + CozeJWTUtil.getJWTForCoze(educationId))
				.build();
		
		try (Response response = HTTP_CLIENT.newCall(request).execute()) {
			if (response.isSuccessful()) {
				if (response.body() != null) {
					String str = response.body().string();
					//System.out.println(str);
					ObjectMapper objectMapper = new ObjectMapper();
					JsonNode jsonNode = objectMapper.readTree(str);
					// 获取access_token的值
					String accessToken = jsonNode.get("access_token").asText();
					//System.out.println(accessToken);
					return accessToken; // 返回获取到的access_token
				} else {
					throw new HttpRequestException("响应体为空");
				}
			} else {
				// 输出错误信息
				String errorMessage = "请求失败: " + response.code() + " " + response.message();
				if (response.body() != null) {
					errorMessage += "\n" + response.body().string();
				}
				throw new HttpRequestException(errorMessage);
			}
		} catch (IOException e) {
			throw new HttpRequestException("请求过程中发生IO异常", e);
		}
	}
	
}
